<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <el-row type="flex" justify="space-between">
          <div class="iInfo"><i class="el-icon-info" style="margin-right:5px;color:#409eff" />总记录数：{{ total }} 条</div>
          <div>
            <el-button size="medium" type="warning">
              <router-link to="/import">
                导入 excel
              </router-link>
            </el-button>
            <el-button size="medium" type="danger" @click="outExcel">导出 excel</el-button>
            <el-button size="medium" type="primary" @click="dialogVisible=true">新增员工</el-button>
          </div>
        </el-row>
      </el-card>
      <el-card style="margin-top:10px">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column
            label="序号"
            width="180"
            type="index"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="220"
            sortable
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            width="220"
            sortable
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            width="180"
            sortable
          />
          <el-table-column
            label="聘用形式"
            width="180"
            sortable
          >
            <template slot-scope="{row}">
              {{ row.formOfEmployment===1? '正式' : '试用' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
            width="180"
            sortable
          />
          <el-table-column
            label="入职时间"
            width="180"
            sortable
          >
            <template slot-scope="{row}">
              {{ dateFormat(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column
            label="转正时间"
            width="180"
            sortable
          >
            <template slot-scope="{row}">
              {{ dateFormat(row.correctionTime) }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push({
                  path:'employees/detail',
                  query:{
                    id:scope.row.id
                  }
                })"
              >查看</el-button>
              <el-button type="text" size="small" @click="allotBoxShow(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top:10px">
          <el-pagination
            :current-page.sync="q.page"
            :page-size="q.size"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 新增&编辑 员工弹框 -->
        <el-dialog
          title="编辑员工"
          :visible.sync="dialogVisible"
          width="50%"
          :before-close="handleClose"
        >
          <emp-dialog :departall="departall" @success="success" />
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog
          v-if="allotVisible"
          title="分配角色"
          :visible.sync="allotVisible"
          width="50%"
        >
          <allot-dialog :allot-id="allotId" @allotClose="allotClose" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import { getUser } from '@/api/user'
import { getDepartments } from '@/api/departments.js'
import { deleteUserDetails } from '@/api/employees'
import empDialog from './empDialog.vue'
// 分配角色对话框
import allotDialog from './allotDialog.vue'
// 转树形结构
import { arrayAsTree } from '@/utils/tree.js'
export default {
  components: {
    empDialog,
    allotDialog
  },
  data() {
    return {
      q: {
        page: 1,
        size: 10
      },
      total: 0,
      tableData: [],
      dialogVisible: false,
      //   部门
      departall: {},
      //   分配角色对话框
      allotVisible: false,
      //   当前角色id
      allotId: ''
    }
  },
  created() {
    this.initUserList()
    // 查询所有部门
    this.initdepartall()
  },
  methods: {
    //   改变分页 页签
    handleCurrentChange(page) {
      this.q.page = page
      this.initUserList()
    },
    // 查看详情
    handleClick(row) {
      console.log(row)
    },
    // 初始化数据
    async initUserList() {
      try {
        const { data } = await getUser(this.q)
        this.total = data.total
        this.tableData = data.rows
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化时间函数
    dateFormat(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    // 弹出框关闭事件
    handleClose() {
      // 清空表单

      // 关闭弹窗
      this.dialogVisible = false
    },
    // 接收传回的响应
    success() {
      this.dialogVisible = false
      this.initUserList()
    },
    // 查询所有部门
    async  initdepartall() {
      const res = await getDepartments()
      if (res.code === 10000) {
        this.departall = arrayAsTree(res.data.depts, '')
      }
    },
    // 中英文表头转换
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })
      //   data把 list中每一个对象转成 对应的 value数组
      data = list.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出excel表
    outExcel() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getUser(this.q.page, this.total)
        const list = res.data.rows
        const { header, data } = this.formatData(list)
        excel.export_json_to_excel({
          header,
          data,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 删除员工信息
    delEmp(id) {
      this.$confirm('该操作将删除该员工信息是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteUserDetails(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          //   刷新页面
          this.initUserList()
        } catch (err) {
          console.log(err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    allotBoxShow(id) {
      this.allotVisible = true
      this.allotId = id
    },
    // 关闭分配角色框
    allotClose() {
      this.allotVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container{
    .iInfo{
        width: 150px;
        height: 40px;
        background-color: #e6f7ff;
        border-radius: 5px;
        border: 2px solid #c4e9ff;
        text-align: center;
        line-height: 40px;
    }
}
</style>
